package com.wkbb.basic.service.impl;

import com.wkbb.basic.mapper.OrgServiceConfigMapper;
import com.wkbb.basic.model.OrgServiceConfig;
import com.wkbb.basic.model.Organization;
import com.wkbb.basic.service.OrgServiceConfigService;
import com.wkbb.basic.service.OrganizationService;
import com.wkbb.basic.service.XmppService;
import com.wkbb.common.base.BaseServiceImpl;
import com.wkbb.common.constants.RedisKeyConstant;
import com.wkbb.common.dto.basic.OrgServiceConfigDto;
import com.wkbb.common.dto.basic.UserDto;
import com.wkbb.common.enums.OrganizationTypeEnum;
import com.wkbb.common.redis.RedisTemplateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 * @author Lilin
 */
@Service
@Slf4j
public class OrgServiceConfigServiceImpl extends BaseServiceImpl<OrgServiceConfig> implements OrgServiceConfigService {

    @Autowired
    private OrgServiceConfigMapper orgServiceConfigMapper;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    @Lazy
    private XmppService xmppService;



    @Override
    public OrgServiceConfig getOrgConfigByOrgId(Long orgId){
        //先从缓存中获取
        //先从redis中查询,查询不到,再从数据库中查询
        OrgServiceConfig redisOrgServiceConfig = (OrgServiceConfig) redisTemplateUtil.get(RedisKeyConstant.WKBB_BASIC_CONFIG+"org:orgId_"+orgId);
        if (null != redisOrgServiceConfig) {
            return redisOrgServiceConfig;
        }
        OrgServiceConfig orgServiceConfig = orgServiceConfigMapper.getByOrgId(orgId);
        if(orgServiceConfig == null){
            orgServiceConfig = new OrgServiceConfig();
            BeanUtils.copyProperties(OrgServiceConfigDto.getDefaultDto(),orgServiceConfig);
            orgServiceConfig.setOrgId(orgId);
            Organization organization = getOrg(orgId);
            //默认幼儿园的看宝宝为显示,其他关闭
            if(organization != null)
            {
                orgServiceConfig.setVideoSwitch(false);
            }

        }else{
            redisTemplateUtil.set(getConfigRedisKey(orgId),orgServiceConfig,RedisKeyConstant.EXPIRATION_TIME_24_HOUR);
        }
        return orgServiceConfig;
    }


    private Organization getOrg(Long orgId){
        try {
            return organizationService.getByPrimaryKey(orgId);
        } catch (Exception e) {
            log.error("查询机构信息有误，{}", e);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 保存机构服务配置信息
     * @param orgServiceConfig 服务配置信息
     * @param userDto 受影响行数
     */
    @Override
    public void saveOrgServiceConfig(OrgServiceConfig orgServiceConfig, UserDto userDto){
        //检测学校是否存在配置信息
        OrgServiceConfig serviceConfig = orgServiceConfigMapper.getByOrgId(orgServiceConfig.getOrgId());

        if(serviceConfig == null){
            orgServiceConfig.setCreateBy(userDto.getName());
            orgServiceConfig.setUpdateBy(userDto.getName());
            orgServiceConfigMapper.insert(orgServiceConfig);
            judgePassRestart(null, orgServiceConfig, 1);
        }else{
            orgServiceConfig.setId(serviceConfig.getId());
            orgServiceConfig.setUpdateBy(userDto.getName());
            orgServiceConfigMapper.update(orgServiceConfig);
            redisTemplateUtil.delete(getConfigRedisKey(orgServiceConfig.getOrgId()));
            judgePassRestart(serviceConfig, orgServiceConfig, 2);
        }
    }

    /**
     * 判断是否需要重启设备（修改幼儿园刷脸通行是才重启）
     * @param source 源数据
     * @param after 修改后的数据
     * @param type 类型 1新增 2修改
     */
    private void judgePassRestart(OrgServiceConfig source, OrgServiceConfig after,Integer type){
        boolean bl;
        if(type == 1){bl=true;}
        else{
            bl = (after.getPassClassTeacher() !=null && !after.getPassClassTeacher().equals(source.getPassClassTeacher())) ||
                 (after.getPassFamily() !=null && !after.getPassFamily().equals(source.getPassFamily())) ||
                 (after.getPassStudent() !=null && !after.getPassStudent().equals(source.getPassStudent()));
        }
        log.info("判断设备是否需要重启设备flag:{},orgId:{}", bl, after.getOrgId());
        if(bl){
            xmppService.restart(after.getOrgId(), null);
        }
    }

    /**
     * 获取学校信息Redis key
     * @param orgId 学校ID
     * @return redis key
     */
    private String getConfigRedisKey(Long orgId){
        return RedisKeyConstant.WKBB_BASIC_CONFIG+"org:orgId_"+orgId;
    }
}
